﻿using Microsoft.Extensions.Options;
using PMIS.Shared.DTO;
using PMIS.Shared.Models;
using PMIS.WebApi.Helpers;
using PMIS.WebApi.Model;
using SqlSugar;
using System.Linq.Expressions;

namespace PMIS.WebApi.Services
{
    public class UserService : BaseService<User>, IUserService
    {
        private readonly AppSettings _appSettings;

        public UserService(IOptions<AppSettings> appSettings)
        {
            _appSettings = appSettings.Value;
        }

        public async Task<AuthenticateUser?> Login(string username, string password)
        {
            var user = await SugarClient.Queryable<User>().SingleAsync(i => i.UserName == username && i.Password == password);
            if (user == null)
                return null;

            // authentication successful so generate jwt token
            var token = await JwtTokenHelper.generateJwtToken(user.Id, _appSettings);

            return new AuthenticateUser()
            {
                Id = user.Id,
                Username = user.UserName,
                RoleId = user.RoleId,
                Token = token
            };
        }

        public override async Task<PagingModel<User>> GetEntityListAsync(int? pageNum, int? pageSize, Expression<Func<User, bool>>? predicate)
        {
            ISugarQueryable<User> queryable;
            if (predicate == null)
            {
                queryable = SugarClient.Queryable<User>()
                    .LeftJoin<Department>((u, d) => u.DepartmentId == d.Id)
                    .Select((u, d) => new User { DepartmentName = d.Name }, true);
            }
            else
            {
                queryable = SugarClient.Queryable<User>()
                    .LeftJoin<Department>((u, d) => u.DepartmentId == d.Id)
                    .Where(predicate)
                    .Select((u, d) => new User { DepartmentName = d.Name }, true);
            }

            RefAsync<int> totalCount = 0;

            List<User> items;

            if (pageNum.HasValue && pageSize.HasValue)
            {
                // Paginated query
                items = await queryable.ToPageListAsync(pageNum.Value, pageSize.Value, totalCount);
            }
            else
            {
                // Non-paginated query, return all items
                items = await queryable.ToListAsync();
                totalCount = items.Count;
            }

            return new PagingModel<User>
            {
                Count = totalCount,
                Items = items
            };
        }
    }
}
